// TorrentDetail.jsx
import { useState, useEffect } from "react";
import { useLoaderData, useNavigate } from "react-router-dom";
import {
  Spin,
  Card,
  Tag,
  Button,
  message,
  Input,
  List,
  Space,
  Avatar,
  Rate,
  Empty,
  Modal,
  Radio,
  Alert,
  Skeleton
} from "antd";
import { DownloadOutlined, LikeOutlined, LikeFilled } from "@ant-design/icons";
import "./home.styl";
import axios from "axios";
import { getAuthToken } from "@/router/index.jsx";
import { returnUserCheckApi } from "@/api/index.jsx";

const TorrentDetail = () => {
  const { validId } = useLoaderData();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [torrentData, setTorrentData] = useState(null);
  const [commentText, setCommentText] = useState("");
  const [commentRating, setCommentRating] = useState(0);
  const [hasRated, setHasRated] = useState(false);
  const [showRatingModal, setShowRatingModal] = useState(false);
  const [selectedRating, setSelectedRating] = useState(0);
  // 是否为回归用户
  const [isReturnUser, setIsReturnUser] = useState(false);
  // 评论数据
  const [comments, setComments] = useState([]);
  // 评论加载状态
  const [loadingComments, setLoadingComments] = useState(false);

  // 折扣券相关状态
  const [showDiscountModal, setShowDiscountModal] = useState(false);
  const [discountCoupons, setDiscountCoupons] = useState([]);
  const [selectedCoupon, setSelectedCoupon] = useState(null);
  const [loadingCoupons, setLoadingCoupons] = useState(false);

  const formatBytes = (bytes) => {
    if (!bytes) return "0 Bytes";
    const k = 1024;
    const units = ["B", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2) + " " + units[i]);
  };

  // 获取用户折扣券
  const fetchDiscountCoupons = async () => {
    setLoadingCoupons(true);
    try {
      const response = await axios.get(
          "http://192.168.55.192:8080/api/promotion/my-discount-coupons",
          {
            headers: { Authorization: `${getAuthToken()}` },
          }
      );

      if (response.data.code === 200) {
        setDiscountCoupons(response.data.data || []);
      } else {
        message.error(response.data.message || "获取折扣券失败");
      }
    } catch (error) {
      console.error("获取折扣券失败:", error);
      message.error("获取折扣券失败，请稍后重试");
    } finally {
      setLoadingCoupons(false);
    }
  };

  // 带折扣券的下载函数
  const handleDownloadWithCoupon = async () => {
    try {
      const params = selectedCoupon ? { discountCouponId: selectedCoupon } : {};

      const response = await axios.get(
          `http://192.168.55.192:8080/api/torrent/download/${validId}`,
          {
            headers: { Authorization: `${getAuthToken()}` },
            params: params,
            responseType: "blob",
          }
      );

      // 解析文件名
      const contentDisposition = response.headers["content-disposition"];
      let filename = `torrent_${validId}.torrent`;
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
        if (filenameMatch) filename = filenameMatch[1];
      }

      // 创建下载链接
      const blob = new Blob([response.data]);
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", filename);
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
      window.URL.revokeObjectURL(url);

      message.success("下载已开始");
      setShowDiscountModal(false);
      setSelectedCoupon(null);
    } catch (error) {
      if (error.response?.status === 404) {
        message.error("资源不存在");
      } else if (error.response?.status === 403) {
        message.error("分享率过低，无法下载新种子");
      } else {
        message.error("下载失败，请检查网络或权限");
      }
      setShowDiscountModal(false);
    }
  };

  // 打开折扣券选择模态框
  const openDiscountModal = () => {
    setShowDiscountModal(true);
    if (discountCoupons.length === 0) {
      fetchDiscountCoupons();
    }
  };

  // 获取种子详情
  const fetchTorrentDetail = async () => {
    try {
      const response = await axios.get(
          `http://192.168.55.192:8080/api/torrent/${validId}`,
          {
            headers: { Authorization: `${getAuthToken()}` },
          }
      );

      if (response.data.code !== 200) {
        message.error("资源不存在");
        navigate("/");
        return;
      }

      const apiData = response.data.data;

      // 转换API数据结构
      const transformedData = {
        id: apiData.id,
        name: apiData.name,
        category: apiData.category,
        size: formatBytes(apiData.size),
        createdAt: new Date(apiData.createdAt).toLocaleString(),
        description: apiData.description,
        downloads: apiData.downloadCount,
        seeders: apiData.seederCount,
        tags: apiData.tags?.split(",") || [],
        uploader: {
          name: apiData.uploaderName || "未知用户",
          avatar: "https://randomuser.me/api/portraits/men/1.jpg", // 默认头像
        },
        // 移除评论数据，因为我们将从独立接口获取
      };

      setTorrentData(transformedData);

      // 检查用户是否为回归用户
      try {
        // 实际项目中应该调用真实API：returnUserCheckApi()
        // 这里模拟API调用结果
        setTimeout(() => {
          setIsReturnUser(Math.random() > 0.5);
        }, 500);
      } catch (err) {
        console.error("检查回归用户状态失败", err);
      }

    } catch (error) {
      message.error("数据加载失败");
    } finally {
      setLoading(false);
    }
  };

  // 获取评论列表
  const fetchComments = async () => {
    setLoadingComments(true);
    try {
      const response = await axios.get(
          `http://192.168.55.192:8080/api/comments/torrent/${validId}`,
          {
            headers: { Authorization: `${getAuthToken()}` },
          }
      );

      if (response.data.code === 200) {
        setComments(response.data.data.comments || []);
      } else {
        message.error("获取评论失败");
      }
    } catch (error) {
      message.error("获取评论失败");
    } finally {
      setLoadingComments(false);
    }
  };

  useEffect(() => {
    // 加载数据
    fetchTorrentDetail();
    fetchComments();
  }, [validId, navigate]);

  const validateRating = (rating) => rating >= 0.5;

  // 提交评分（独立评分）
  const handleRate = async (rating) => {
    if (!validateRating(rating)) {
      message.warning("请至少选择0.5星进行评分");
      return false;
    }

    try {
      // 调用后端评分接口
      const response = await axios.post(
          "http://192.168.55.192:8080/api/comments",
          {
            torrentId: validId,
            rating: rating,
            comment: "", // 独立评分不需要评论内容
          },
          {
            headers: { Authorization: `${getAuthToken()}` },
          }
      );

      if (response.data.code === 200) {
        message.success("评分成功");
        setHasRated(true);
        // 刷新评论列表（包含评分）
        fetchComments();
        return true;
      } else {
        message.error(response.data.message || "评分失败");
        return false;
      }
    } catch (error) {
      message.error("评分请求失败");
      return false;
    }
  };

  // 处理点赞/取消点赞
  const handleLike = async (commentId, isLiked) => {
    try {
      if (isLiked) {
        // 取消点赞
        await axios.delete(
            `http://192.168.55.192:8080/api/comments/${commentId}/like`,
            {
              headers: { Authorization: `${getAuthToken()}` },
            }
        );
        message.success("取消点赞成功");
      } else {
        // 点赞
        await axios.post(
            `http://192.168.55.192:8080/api/comments/${commentId}/like`,
            {},
            {
              headers: { Authorization: `${getAuthToken()}` },
            }
        );
        message.success("点赞成功");
      }

      // 刷新评论列表
      fetchComments();
    } catch (error) {
      message.error(error.response?.data?.message || "操作失败");
    }
  };

  // 提交评论（可能包含评分）
  const handleCommentSubmit = async () => {
    if (!commentText.trim()) {
      message.warning("请输入评论内容");
      return;
    }

    try {
      // 调用后端添加评论接口
      const response = await axios.post(
          "http://192.168.55.192:8080/api/comments",
          {
            torrentId: validId,
            rating: commentRating > 0 ? commentRating : undefined,
            comment: commentText,
          },
          {
            headers: { Authorization: `${getAuthToken()}` },
          }
      );

      if (response.data.code === 200) {
        message.success("评论提交成功");
        setCommentText("");
        setCommentRating(0);
        // 刷新评论列表
        fetchComments();
      } else {
        message.error(response.data.message || "评论提交失败");
      }
    } catch (error) {
      message.error("评论请求失败");
    }
  };

  // 独立评分弹窗处理
  const handleModalRate = async () => {
    if (!validateRating(selectedRating)) {
      message.warning("请至少选择0.5星进行评分");
      return;
    }

    const success = await handleRate(selectedRating);
    if (success) {
      setShowRatingModal(false);
      setSelectedRating(0);
    }
  };

  return (
      <div className="torrent-detail">
        <Spin spinning={loading} tip="加载中..." size="large">
          {torrentData && (
              <Card className="detail-card">
                <div className="header-section">
                  <div className="uploader-info">
                    <Avatar
                        src={torrentData.uploader.avatar}
                        size={48}
                        className="uploader-avatar"
                    />
                    <div className="title-wrapper">
                      <div className="title-row">
                        <h1 className="resource-title">{torrentData.name}</h1>
                        <Tag color="blue" className="category-tag">
                          {torrentData.category}
                        </Tag>
                      </div>
                      <div className="meta-line">
                        <span>由</span>
                        <Tag color="geekblue">{torrentData.uploader.name}</Tag>
                        <span>• 发布于 {torrentData.createdAt}</span>
                      </div>
                      {/* 评分信息需要从评论接口获取 */}
                    </div>
                  </div>

                  <Space>
                    <Button
                        type="primary"
                        icon={<DownloadOutlined />}
                        onClick={openDiscountModal}
                        style={{ position: "relative" }}
                    >
                      下载资源
                      {isReturnUser && (
                          <Tag
                              color="orange"
                              style={{
                                position: "absolute",
                                right: -10,
                                top: -10,
                                transform: "rotate(20deg)",
                                fontSize: "12px",
                                padding: "0 6px",
                                boxShadow: "0 2px 4px rgba(0,0,0,0.2)",
                                border: "1px solid #ffa940",
                              }}
                          >
                            半价
                          </Tag>
                      )}
                    </Button>
                    <Button
                        type="primary"
                        onClick={() => setShowRatingModal(true)}
                        disabled={hasRated}
                    >
                      {hasRated ? "已评分" : "我要评分"}
                    </Button>
                  </Space>
                </div>

                <div className="content-section">
                  {/* 评分模态框 */}
                  <Modal
                      title="资源评分"
                      open={showRatingModal}
                      onOk={handleModalRate}
                      onCancel={() => {
                        setShowRatingModal(false);
                        setSelectedRating(0);
                      }}
                      okText="提交评分"
                      cancelText="取消"
                  >
                    <div style={{ padding: "20px 0", textAlign: "center" }}>
                      <Rate
                          allowHalf
                          value={selectedRating}
                          onChange={(v) => setSelectedRating(v)}
                          style={{ fontSize: 32 }}
                      />
                      <div style={{ marginTop: 8, color: "#666" }}>
                        {selectedRating > 0
                            ? `当前评分：${selectedRating}星`
                            : "请选择0.5星及以上进行评分"}
                      </div>
                    </div>
                  </Modal>

                  {/* 折扣券选择模态框 */}
                  <Modal
                      title="使用折扣券"
                      open={showDiscountModal}
                      onOk={handleDownloadWithCoupon}
                      onCancel={() => {
                        setShowDiscountModal(false);
                        setSelectedCoupon(null);
                      }}
                      okText="确认下载"
                      cancelText="取消"
                      width={600}
                  >
                    <div style={{ marginBottom: 16 }}>
                      <Alert
                          message="选择折扣券可以享受下载优惠"
                          type="info"
                          showIcon
                      />
                    </div>

                    <Spin spinning={loadingCoupons}>
                      <div style={{ maxHeight: 400, overflowY: 'auto' }}>
                        <Radio.Group
                            value={selectedCoupon}
                            onChange={(e) => setSelectedCoupon(e.target.value)}
                            style={{ width: '100%' }}
                        >
                          {discountCoupons.length > 0 ? (
                              discountCoupons.map(coupon => (
                                  <Radio
                                      key={coupon.id}
                                      value={coupon.id}
                                      style={{
                                        display: 'block',
                                        height: '60px',
                                        lineHeight: '60px',
                                        border: '1px solid #e8e8e8',
                                        borderRadius: '4px',
                                        marginBottom: '10px',
                                        padding: '0 16px',
                                        backgroundColor: selectedCoupon === coupon.id ? '#e6f7ff' : '#fff'
                                      }}
                                  >
                                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                      <div>
                                        <span style={{ fontWeight: 'bold' }}>{coupon.discountRate}折</span>
                                        <span style={{ marginLeft: 10, color: '#666' }}>优惠券</span>
                                      </div>
                                      <div>
                                    <span style={{ color: '#999' }}>
                                      有效期至 {new Date(coupon.expiredAt).toLocaleDateString()}
                                    </span>
                                      </div>
                                    </div>
                                  </Radio>
                              ))
                          ) : (
                              <div style={{ textAlign: 'center', padding: '20px' }}>
                                {loadingCoupons ? (
                                    <Skeleton active paragraph={{ rows: 3 }} />
                                ) : (
                                    <Empty
                                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                                        description="暂无可用折扣券"
                                    />
                                )}
                              </div>
                          )}
                        </Radio.Group>
                      </div>
                    </Spin>

                    <div style={{ marginTop: 16 }}>
                      <Radio
                          value={null}
                          checked={selectedCoupon === null}
                          onChange={() => setSelectedCoupon(null)}
                      >
                        不使用折扣券
                      </Radio>
                    </div>
                  </Modal>

                  <div className="description-block">
                    <h3 className="section-title">资源描述</h3>
                    <div className="description-content">
                      {torrentData.description}
                    </div>
                  </div>

                  <div className="stats-block">
                    <div className="stat-item">
                      <span className="stat-label">文件大小</span>
                      <span className="stat-value">{torrentData.size}</span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">下载次数</span>
                      <span className="stat-value">{torrentData.downloads}次</span>
                    </div>
                    <div className="stat-item">
                      <span className="stat-label">做种人数</span>
                      <span className="stat-value">{torrentData.seeders}人</span>
                    </div>
                  </div>

                  <div className="tag-section">
                    {torrentData.tags?.map((tag, i) => (
                        <Tag key={i} color={["geekblue", "green", "orange"][i % 3]}>
                          {tag}
                        </Tag>
                    ))}
                  </div>

                  <div className="comment-section">
                    <h3 className="section-title">
                      用户讨论（{comments.length || 0}条）
                    </h3>

                    <div className="comment-editor">
                      <Space direction="vertical" style={{ width: "100%" }}>
                        <Input.TextArea
                            rows={4}
                            value={commentText}
                            onChange={(e) => setCommentText(e.target.value)}
                            placeholder="写下你的使用体验..."
                            maxLength={200}
                            showCount
                        />
                        <Space align="center">
                          <Rate
                              allowHalf
                              value={commentRating}
                              onChange={(v) => setCommentRating(v)}
                              style={{ marginRight: 16 }}
                          />
                          <Button
                              type="primary"
                              onClick={handleCommentSubmit}
                              disabled={!commentText.trim()}
                          >
                            发表评论
                          </Button>
                          <span style={{ color: "#999", fontSize: 12 }}>
                        {commentRating > 0
                            ? `已选评分：${commentRating}星`
                            : "可选评分（0.5星起）"}
                      </span>
                        </Space>
                      </Space>
                    </div>

                    <Spin spinning={loadingComments}>
                      <List
                          dataSource={comments}
                          locale={{
                            emptyText: <Empty description="暂无评论，快来抢沙发～" />,
                          }}
                          renderItem={(item) => (
                              <List.Item className="comment-item">
                                <Avatar src="https://randomuser.me/api/portraits/men/1.jpg" size="large" />
                                <div className="comment-content">
                                  <div className="comment-header">
                                    <Space>
                                      <span className="username">{item.username}</span>
                                      {item.rating && (
                                          <Rate
                                              disabled
                                              allowHalf
                                              value={item.rating}
                                              style={{ fontSize: 14 }}
                                          />
                                      )}
                                    </Space>
                                    <span className="comment-time">
                              {new Date(item.createdAt).toLocaleString()}
                            </span>
                                  </div>
                                  <p className="comment-text">{item.comment}</p>
                                  <div className="comment-actions">
                                    <Button
                                        icon={item.isLiked ? <LikeFilled /> : <LikeOutlined />}
                                        onClick={() => handleLike(item.id, item.isLiked)}
                                        type={item.isLiked ? "primary" : "default"}
                                    >
                                      {item.likeCount || 0}
                                    </Button>
                                  </div>
                                </div>
                              </List.Item>
                          )}
                      />
                    </Spin>
                  </div>
                </div>
              </Card>
          )}
        </Spin>
      </div>
  );
};

export default TorrentDetail;